package com.primaryedu.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.google.gson.Gson;
import com.primaryedu.R;
import com.primaryedu.ui.MainActivity;
import com.primaryedu.ui.VideoCallActivity;
import com.primaryedu.bean.VideoBean;
import com.primaryedu.data.GlobalData;
import com.primaryedu.data.HigtApplication;
import com.primaryedu.ui.app.growstep.VideoActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Thomas_yang on 2018/12/8.
 */

public class MessageService extends Service {
    //获取消息线程
    private MessageThread messageThread = null;

    //点击查看
    private Intent messageIntent = null;
    private PendingIntent messagePendingIntent = null;

    //通知栏消息
    private int messageNotificationID = 1000;
    //    private Notification messageNotification = null;
    private NotificationManager messageNotificatioManager = null;
    private Notification.Builder builder;
    private HigtApplication application;
    private String serverMessage = null;
    private VideoBean videobean;

    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        application = (HigtApplication) getApplication();
        //初始化
        messageNotificatioManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        builder = new Notification.Builder(this);
        builder.setContentInfo("");
        builder.setContentText("您的孩子正在邀请你视频通话");//设置内容
        builder.setContentTitle("铁心桥小学");//设置标题
        builder.setSmallIcon(R.drawable.logo);//设置状态栏显示时的图标
        builder.setTicker("新消息");//在状态栏显示的标题
        builder.setAutoCancel(true);
        builder.setWhen(System.currentTimeMillis());
        builder.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音，振动方式，灯光

//        messageNotification = new Notification();
//        messageNotification.icon = R.drawable.logo;
//        messageNotification.tickerText = "新消息";
//        messageNotification.defaults = Notification.DEFAULT_SOUND;

    /*    UserResponse userResponse = new UserResponse();
        userResponse.setUserid(GlobalData.getUserId(this));
        userResponse.setUserroleid("2");//用户角色 0：主讲 1：助教 2: 学员 3：直播用户 4:巡检员　10:系统管理员　11:平台管理员　12:企业管理员 14:二级代理
        userResponse.setFirstname(GlobalData.getUserId(this));
        application.setCurrentUser(userResponse);
        if (GlobalData.getSerial(this) != null)
            RoomActivity.toAction(this,
                    GlobalData.getSerial(this),
                    "",
                    "铁心桥小学",
                    "0");*/
        messageIntent = new Intent(this, VideoCallActivity.class);
        messagePendingIntent = PendingIntent.getActivity(this, 0, messageIntent, 0);

        //开启线程
        messageThread = new MessageThread();
        messageThread.isRunning = true;
        messageThread.start();

        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 从服务器端获取消息
     */
    class MessageThread extends Thread {
        //运行状态，下一步骤有大用
        public boolean isRunning = true;

        public void run() {
            while (isRunning) {
                try {
                    //休息1分钟
                    Thread.sleep(20000);
                    //获取服务器消息
                    getServerMessage();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *
     *
     * @return 返回服务器要推送的消息，否则如果为"0"的话，不推送
     */
    public void getServerMessage() {
        String url = "https://njtx.njtxqxx.com/rest/user/getUseridSelectUser";
        Map<String, String> params = new HashMap<>();
        System.out.println("id==" + GlobalData.getUserId(this));
        params.put("id",GlobalData.getUserId(this) );
        OkHttpUtils.post()//
                .url(url)
                .params(params)
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("responseVideo==" + response);
                        Gson gson = new Gson();
                        videobean = gson.fromJson(response, VideoBean.class);
                        int result = videobean.getResult();
                        if (result == 1) {
//                                    serverMessage = "YES!";
                            serverMessage = videobean.getData().getList().get(0).getStatus();
                            Log.i("yy","status======" + serverMessage);
                            if ("1".equals(serverMessage)) {
                                //更新通知栏
                                builder.setContentIntent(messagePendingIntent);
//                        messageNotification.setLatestEventInfo(MessageService.this,
//                                "新消息","奥巴马宣布,本拉登兄弟挂了!"+serverMessage,messagePendingIntent);
                                Notification notification = builder.build();
                                messageNotificatioManager.notify(messageNotificationID, notification);
                                //每次通知完，通知ID递增一下，避免消息覆盖掉
//                        messageNotificationID++;
                            }
                        }

                    }
                });
    }
}
